<?php
/* $Id: packs.php 14 2009-04-11 17:40:34Z ronan $ */
/*
 * Design:
 * 
 * packages db table:
 * packID, packName, typeIDList, timeCreated, creatorName, packType[private, public]
 *
 * 
 * packs.php includes options for "View Your Packages" "Create New Package" "Find other packages"
 * View yours: 
 * 		pack name with list of items for each pack
 * 		"Add to Cart", "Edit", "Delete" options
 * 				Edit will have a renamable name box, "Public/Private" option, and a cart-like interface
 * Create New:
 * 		List cart contents, offer checkboxes for "which to include"
 * Find Others:
 * 		Search database for public (by name? By included item? Both. Do both.) 
 */

$basesite=$_SERVER['PHP_SELF'];
require("common.php");
require("auth.php");
require("header.php");

echo "<a href=\"packs.php?f=viewyours\">View Your Packages</a> | <a href=\"packs.php?f=createnew\">Create New Package</a> | <a href=\"packs.php?f=findothers\">Find Other Packages</a><br /><br />\n\n";
$f = (empty($_GET['f'])?'viewyours':$_GET['f']);
if(!empty($_POST['f'])) $f=$_POST['f'];

if($f=="viewyours") {
	$packs = Query("SELECT * FROM packages WHERE creatorName='$uid'");
	echo "Click a packages name for details and options!<br /><br /><br />\n\n\n";
	if(!mysql_num_rows($packs)) echo "You do not have any packages saved!";
	while($l = mysql_fetch_array($packs)) {
		echo "<b><a href=\"packs.php?f=view&id=".$l['packID']."\"><font color=\"aaaaff\">".$l['packName']."</font></a> - ".($l['packType']=='public'?'<font color="green">public</font>':'<font color="red">private</font>')."</b><br /><br />\n\n";
	}
	require("footer.php");
	exit;
} //END View Yours
if($f=="createnew") {
	echo "Packages are created based on items in your cart. So go change the cart if you want to change these items.<br /><br />\n\n";
	$orders = Query("SELECT * FROM orders WHERE customerID='$uidnum' AND status='in cart'");
	if(!mysql_num_rows($orders)) {
		echo "Your cart is empty!<br /><br />\n\n";
	} else {
		$total=0;
		$i=0;
		echo "Your cart has the following items in it:<br /><br />\n\n";
		echo "<form method=\"POST\" action=\"packs.php\">\n";
		echo "<table border=0 cellspacing=0 cellpadding=2><tr><td align=\"center\" width=\"75\"><b>Item</b></td><td align=\"center\" width=\"125\"><b>Qty.</b></td><td align=\"center\" width=\"90\"><b>Per Unit</b></td><td align=\"center\" width=\"90\"><b>Total</b></td></tr>\n";
		while ($line = mysql_fetch_array($orders, MYSQL_ASSOC)) {
			if($line['usingStock']==3) continue;
			$total+=$line['priceTotal'];
			$itemarray[$i]=$line['typeID'].'x'.$line['quantity'];
			echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
			$bgcolor= !$bgcolor;
			echo "\t" .
    				"<td align=\"center\" width=\"75\">".$line['typeName']."</td>\t" .
    				"<td align=\"center\" width=\"125\">".addCommas($line['quantity']).($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .
    				"<td align=\"center\" width=\"90\">".addCommas($line['pricePerUnit'])." per ".addCommas($line['quantityModifier'])." </td>\t" .
    				"<td align=\"center\" width=\"90\">".addCommas($line['priceTotal'])."</td>\t" .
    				"</tr>\n";
    		$i++;
		}
		echo "</table><br />\n" .
				"Total cost: ".addCommas($total)." ISK<br />\n" .
				"Package name: " .
				"<input type=\"text\" name=\"name\" size=\"20\" /><br />\n" .
				"Package Type: Public <input type=\"radio\" name=\"type\" value=\"public\" checked />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Private: <input type=\"radio\" name=\"type\" value=\"private\" /><br />\n" .
				generateHiddenFields(array('f'=>'confirmnew', 'items'=>implode(',',$itemarray))) .
				"<input type=\"submit\" value=\"Create Package\" /></form>\n";
	}
	require("footer.php");
	exit;
} //END Create New
if($f=="findothers") {
	$page=(!empty($_GET['page'])?$_GET['page']:1);
	$searchstr=(!empty($_GET['q'])?" AND packName LIKE '%".implode('%',explode(' ',$_GET['q']))."%'":'');
	$searcharg=(!empty($_GET['q'])?'&q='.$_GET['q']:'');
	$packs = Query("SELECT * FROM packages WHERE packType='public'".$searchstr);
	$perpage = 30;
	if(!mysql_num_rows($packs)) {
		echo "No packages found!";
		require('footer.php');
		exit;
	}
	$numPages=(mysql_num_rows($packs)-(mysql_num_rows($packs)%$perpage)) / $perpage + 1;
	echo "Go to page: ";
	for($i=1;$i<=$numPages;$i++) {
		echo "<a href=\"packs.php?f=findothers&page=$i".$searcharg."\">$i</a> ";
	}
	echo "<br /><br />\n\n";
	echo "<form method=\"GET\" action=\"packs.php\"><input type=\"text\" size=\"30\" name=\"q\">".generateHiddenFields(array('f'=>'findothers', 'page'=>1))."<input type=\"submit\" value=\"Search by Package Name\"></form><br />\n";
	$count=0;
	echo "Click a package's name for details/options!<br /><br /><br />\n\n\n";
	while($l = mysql_fetch_array($packs)) {
		if($count<$perpage*($page-1)) {$count++; continue;}
		if($count>=$perpage*$page) break;
		echo "<b><a href=\"packs.php?f=view&id=".$l['packID']."\"><font color=\"aaaaff\">".$l['packName']."</font></a></b> - <i>Added by <b>".$l['creatorName']."</b></i><br /><br />\n\n";
		$count++;
	}
	require("footer.php");
	exit;
} //END Find others
if($f=="confirmnew") {
	if(empty($_POST['name']) || empty($_POST['items']) || empty($_POST['type'])) {
		echo "ERROR: Information is missing from POST data (Possibly you omitted the name field)";
	}
	$name=addslashes($_POST['name']);
	$type=$_POST['type'];
	$typeIDList=$_POST['items'];
	Query("INSERT INTO packages (packName, typeIDList, timeCreated, creatorName, packType) VALUES('$name', '$typeIDList', NOW(), '$uid', '$type')");
	echo "Pack added!";
	require("footer.php");
	exit;
}
if($f=="delete") {
	if(empty($_GET['id'])) {
		echo "No id specified for deletion.";
		require('footer.php');
		exit;
	}
	$id=addslashes($_GET['id']);
	$pack = mysql_fetch_array(Query("SELECT * FROM packages WHERE packID='$id' LIMIT 1"));
	if($pack['creatorName'] != $uid) {
		if($userLevel=='admin') {
			echo "This isn't your package - but you're an admin, so you can delete it anyway. Be careful!<br />\n<br />\n";
		} else {
			echo "This isn't your package - you cannot delete it!";
			require('footer.php');
			exit;
		}
	} 
	echo "You have chosen to delete the package <font color=\"yellow\">".$pack['packName']."</font>.<br /><br />\n\n";
	echo generateButton("Confirm Deletion", "POST", array('f'=>'confirmdelete', 'id'=>$id));
	require('footer.php');
	exit;
}
if($f=="confirmdelete") {
	if(empty($_POST['id'])) {
		echo "No id specified for deletion.";
		require('footer.php');
		exit;
	}
	$id=addslashes($_POST['id']);
	$pack = mysql_fetch_array(Query("SELECT * FROM packages WHERE packID='$id' LIMIT 1"));
	if($pack['creatorName'] != $uid) {
		if($userLevel=='admin') {
			echo "This isn't your package - but you're an admin, so you can delete it anyway. Be careful!<br />\n<br />\n";
		} else {
			echo "This isn't your package - you cannot delete it!";
			require('footer.php');
			exit;
		}
	} 
	Query("DELETE FROM packages WHERE packID='$id' LIMIT 1");
	echo "Package deleted!";
	require('footer.php');
	exit;
}
if($f=="edit") {
	if(empty($_GET['id'])) {
		echo "No id specified for editting.";
		require('footer.php');
		exit;
	}
	$id=$_GET['id'];
	$pack = mysql_fetch_array(Query("SELECT * FROM packages WHERE packID='$id' LIMIT 1"));
	if($pack['creatorName'] != $uid) {
		if($userLevel=='admin') {
			echo "This isn't your package - but you're an admin, so you can edit it anyway. Be careful!<br />\n<br />\n";
		} else {
			echo "This isn't your package - you cannot edit it!";
			require('footer.php');
			exit;
		}
	} 
	//BEGIN DISPLAY CODE
	
	$itemArray=itemListToArray($pack['typeIDList']);
	$items = getItemsByIdQueryList(itemArrayToQueryList($itemArray));
	$count=0;
	echo "<form method=\"POST\" action=\"packs.php\">";
	echo "<b><input type=\"text\" name=\"name\" value=\"".strtr($pack['packName'],'"',"'")."\" size=\"40\" /><br />\n"
	."Package Type: <font color=\"green\"><b>Public</b></font> <input type=\"radio\" name=\"type\" value=\"public\" ".($pack['packType']=='public'?'checked ':'')."/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"red\"><b>Private</b></font> <input type=\"radio\" name=\"type\" value=\"private\" ".($pack['packType']=='private'?'checked ':'')."/><br />\n";
	echo "<table border=0 cellspacing=0 cellpadding=2><tr><td></td><td><b>Name</b></td><td><b>Price</b></td><td><b>Availability</b></td><td><b>Quantity</b></td></tr>\n";
	while($i = mysql_fetch_array($items)) { //Go through items in current pack
		//Set unOrderable to 1 if its marketgroup or any parent marketgroups are unbuildable
		$cmid = $i['marketGroupID'];
		$unOrderable=0;
		while($cmid!="NULL" && $cmid!="") {
			$mg = getMarketGroupById($cmid);
			if(mysql_result($mg, 0, 'isBuildable')==0) {$unOrderable=1; break;}
			$cmid=mysql_result($mg,0,'parentGroupID');
		}
		
		
		$typeID=$i['typeID'];
		$gfx=getGraphicPath($typeID);
		$imgsize=getImgsize($typeID);
		echo ($bgcolored?"<tr class=\"itemtablecolor1\">":"<tr class=\"itemtablecolor2\">"); $bgcolored= !$bgcolored;
		echo "<!--ID: ".$i['typeID']."-->\t" .
			"<td width=\"$imgsize\"><img width=\"$imgsize\" height=\"$imgsize\" src=\"$gfx\" /></td>\t" .
			"<td width=\"150\">".($ingame?'<a href="showinfo:'.$i['typeID'].'">':'').$i['typeName'].($ingame?'</a>':'')."</td>\t";
		
		echo "<td width=\"125\">".addCommas($i['price'])." per ".addCommas($i['quantityModifier'])."</td>\t"; 
		echo "<td width=\"125\">";
		echo displayAvailability($i['numAvailable'],$i['isBuildable'],$i['isSpecialOrderable'] && !$unOrderable);
		echo "</td>\t";	
		echo "<td>".addCommas($itemArray[$i['typeID']]).($i['quantityModifier']==1?'':"x".addCommas($i['quantityModifier']))."</td>";		
		echo "</tr>\n";
		$count++;
	}
	echo "</table>";
		//END DISPLAY CODE
	echo generateHiddenFields(array('f'=>'confirmedit', 'id'=>$id))."<input type=\"submit\" value=\"Confirm Changes\" /></form>";
	require('footer.php');
	exit;
} //END EDIT
if($f=='confirmedit') {
	if(empty($_POST['name']) || empty($_POST['id']) || empty($_POST['type'])) {
		echo "ERROR: Information is missing from POST data (Possibly you omitted the name field)";
	}
	$name=addslashes($_POST['name']);
	$type=$_POST['type'];
	$id=$_POST['id'];
	Query("UPDATE packages SET packName='$name', packType='$type' WHERE packID='$id' LIMIT 1");
	echo "Pack updated!";
	require("footer.php");
	exit;
}
if($f=='add') {
	if(empty($_GET['id'])) {
		echo "No id specified to add.";
		require('footer.php');
		exit;
	}
	$packID=$_GET['id'];
	$pack = mysql_fetch_array(Query("SELECT * FROM packages WHERE packID='$packID' LIMIT 1"));
	$itemArray=itemListToArray($pack['typeIDList']);
	foreach($itemArray as $id=>$qty) {
		$item = getItemById($id);
		$quantityModifier = mysql_result($item,0,'quantityModifier');
		$name=mysql_result($item, 0, 'typeName');
		$price=mysql_result($item, 0, 'price');
		$numAvailable=mysql_result($item, 0, 'numAvailable');
		$isBuildable=mysql_result($item,0,'isBuildable');
		$isSpecialOrderable = mysql_result($item,0,'isSpecialOrderable');
		if(($numAvailable<=0 && !$isBuildable && !$isSpecialOrderable) || !isBuildableMarketTree(mysql_result($item,0,'marketGroupID'))) {
			echo "$qty x $quantityModifier \"$name\"".($qty*$quantityModifier==1?' has':'s have')." <font color=\"red\">NOT</font> been added to the cart.<br />\nThis item cannot currently be ordered. Sorry!<br /><br />\n\n";
			continue;
		}
		$specialorder=($numAvailable<=0&&$isBuildable==0&&$isSpecialOrderable==1?2:0);
		$orders=Query("SELECT * FROM orders WHERE customerID=$uidnum AND status='in cart'");
		$q=0; $err=0;
		if(!is_number($qty) || $qty<1 || $qty>$maxQuantity) {
			echo "ERROR: bad quantity!";
			require("footer.php");
			exit;
		}
		while($l=mysql_fetch_array($orders)) {
			if( $id==$l['typeID'] ) {
				$newqty = $qty+$l['quantity'];
				if($newqty>$maxQuantity) { echo "ERROR: Adding $qty of this item leaves your cart with more of this item than the allowable maximum. Not added."; require("footer.php"); exit; }
				if(!$isSpecialOrderable && !$isBuildable && $newqty>$numAvailable) { echo "ERROR: We cannot special order this item, and adding $qty of this item leaves your cart with more of this item than we have available. Not added."; $err=1; $q=1; break; }
				$results = Query("UPDATE orders SET quantity=quantity+".$qty.", priceTotal=pricePerUnit*quantity WHERE id='".$l['id']."' LIMIT 1");
				$q=1;
				break;
			}
		}
		if($q!=1 && !$isSpecialOrderable && !$isBuildable && $numAvailable<=0) {
			echo "You can't actually order this item - we can't build it, can't special order it, and don't have any stock of it. If you see this message at all, it's actually a bug - it shouldn't have even shown up in the browse page. Please let Phantom Circuit know :)<br />\n";
			$err=1; $q=1;
		}
		else if($q!=1 && !$isSpecialOrderable && !$isBuildable && $numAvailable>0 && $qty>$numAvailable) {
			echo "We cannot special order this item, so you can only buy as many we have in stock - $numAvailable added to cart.";
			$qty = $numAvailable;
		} 
		else if(!$err) echo "$qty x $quantityModifier \"$name\"".($qty*$quantityModifier==1?' has':'s have')." been added to the cart.<br />\n";
		if(!$q) $results = Query("INSERT INTO orders (typeId, typeName, quantity, quantityModifier, pricePerUnit, priceTotal, customerID, customerName, status, usingStock) VALUES('$id', '$name', '$qty', '$quantityModifier', '$price', '".($price*$qty)."', '$uidnum', '$uid', 'in cart', '$specialorder')");
		if($qty > $numAvailable && !$isBuildable && $isSpecialOrderable) {
			if($numAvailable<=0) echo 'This is a <font color="yellow">special order</font>.<br />'."\n";
			else echo "We have $numAvailable".($quantityModifier==1?'':"x".$quantityModifier)." \"$name\"s in stock, so the rest will be converted into a ".($isBuildable?'build order.':'<font color="yellow">special order</font>.')."<br />\n";
		} else if($qty > $numAvailable && $isBuildable && $numAvailable>0) echo "We have $numAvailable".($quantityModifier==1?'':"x".$quantityModifier)." \"$name\"s in stock, so the rest will be converted into a ".($isBuildable?'build order.':'<font color="yellow">build order</font>.')."<br />\n";
		echo "<br />\n";
	}
	echo "<br />\nPackage added to cart!";
	require('footer.php');
	exit;
} //END ADD
if($f=='view') {
	if(empty($_GET['id'])) {
		echo "No ID to view!";
		require('footer.php');
		exit;
	}
	$id=$_GET['id'];
	$l=mysql_fetch_array(Query("SELECT * FROM packages WHERE packID='$id' LIMIT 1"));
	$itemArray=itemListToArray($l['typeIDList']);
	$items = getItemsByIdQueryList(itemArrayToQueryList($itemArray));
	$count=0;
	if($l['creatorName']==$uid) echo "<b><font color=\"aaaaff\">".$l['packName']."</font> - ".($l['packType']=='public'?'<font color="green">public</font>':'<font color="red">private</font>')."</b><br />\n";
	else echo "<b><font color=\"aaaaff\">".$l['packName']."</font></b> - <i>Added by <b>".$l['creatorName']."</b></i><br />\n";
	echo "<table border=0 cellspacing=0 cellpadding=2><tr><td></td><td><b>Name</b></td><td><b>Price</b></td><td><b>Availability</b></td><td><b>Quantity</b></td></tr>\n";
	$total=0;
	while($i = mysql_fetch_array($items)) { //Go through items in current pack
		//Set unOrderable to 1 if its marketgroup or any parent marketgroups are unbuildable
		$total+=$i['price']*$itemArray[$i['typeID']];
		$cmid = $i['marketGroupID'];
		$unOrderable=0;
		while($cmid!="NULL" && $cmid!="") {
			$mg = getMarketGroupById($cmid);
			if(mysql_result($mg, 0, 'isBuildable')==0) {$unOrderable=1; break;}
			$cmid=mysql_result($mg,0,'parentGroupID');
		}
		$typeID=$i['typeID'];
		$gfx=getGraphicPath($typeID);
		$imgsize=getImgsize($typeID);
		echo ($bgcolored?"<tr class=\"itemtablecolor1\">":"<tr class=\"itemtablecolor2\">"); $bgcolored= !$bgcolored;
		echo "<!--ID: ".$i['typeID']."-->\t" .
			"<td width=\"$imgsize\"><img width=\"$imgsize\" height=\"$imgsize\" src=\"$gfx\" /></td>\t" .
			"<td width=\"150\">".($ingame?'<a href="showinfo:'.$i['typeID'].'">':'').$i['typeName'].($ingame?'</a>':'')."</td>\t";
		
		echo "<td width=\"125\">".addCommas($i['price'])." per ".addCommas($i['quantityModifier'])."</td>\t"; 
		echo "<td width=\"125\">";
		echo displayAvailability($i['numAvailable'],$i['isBuildable'],$i['isSpecialOrderable'] && !$unOrderable);
		echo "</td>\t";	
		echo "<td>".addCommas($itemArray[$i['typeID']]).($i['quantityModifier']==1?'':"x".addCommas($i['quantityModifier']))."</td>";		
		echo "</tr>\n";
		$count++;
	}
	echo "</table>";
	echo "Total cost: ".addCommas($total)."<br /><br />\n\n";
	echo "<a href=\"packs.php?f=add&id=".$l['packID']."\">Add Package to Cart</a>";
	if($l['creatorName']==$uid || $userLevel=='admin') echo " | <a href=\"packs.php?f=edit&id=".$l['packID']."\"><font color=\"yellow\">Edit Package</font></a> | <a href=\"packs.php?f=delete&id=".$l['packID']."\"><font color=\"red\">Delete Package</font></a>";
	echo "<br /><br />\n\n";
	require('footer.php');
	exit;
}

require('footer.php');
exit;
?>